import { AfterViewChecked, Component, ElementRef, EventEmitter, Injector, Output, OnInit, ViewChild, Input } from '@angular/core';
import { AppConsts } from '@shared/AppConsts';
import { ActivatedRoute } from '@angular/router';
import { AppComponentBase } from '@shared/common/app-component-base';
import { ProfileServiceProxy, TaskServiceProxy, WorkflowServiceProxy, OutsourcingWorkFlowServiceProxy, ChooseSupplierViewModel, SupplierQuotationServiceProxy, OutsouringServiceProxy, UserServiceProxy, ProcessingDeliveryDto, ProcessingDeliveryViewDto, ProcessingOutPutDto, SelectItemDto } from '@shared/service-proxies/service-proxies';
import { ModalDirective } from 'ngx-bootstrap';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';
import { TaskService } from '../task/Task.service';
import { accountModuleAnimation } from '@shared/animations/routerTransition';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/components/table/table';
import { PrimengTableHelper } from 'shared/helpers/PrimengTableHelper';
import { SelectItem } from 'primeng/api';
import { forEach } from '@angular/router/src/utils/collection';

@Component({
  selector: 'app-ChooseSupplier',
  templateUrl: './ChooseSupplier.component.html',
  styleUrls: ['./ChooseSupplier.component.css']
})
export class ChooseSupplierComponent extends AppComponentBase implements OnInit {

  @ViewChild('createOrEditModal') modal: ModalDirective;
  @ViewChild('paginator') paginator: Paginator;
  @ViewChild('taskdataTable') taskdataTable: Table;
  @ViewChild('dataTable') dataTable: Table;

  @Input() workflowid: any;
  @Output() out = new EventEmitter();

  isLoading = true;
  rows: number;
  canvasWidth: number;

  active = false;
  saving = false;
  _processingDeliveryDto: ProcessingDeliveryDto = new ProcessingDeliveryDto();
  _processingDeliveryViewDto: ProcessingDeliveryViewDto[];
  detailsprimengTableHelper: PrimengTableHelper;

  workflow: any;
  datatablevalues: ChooseSupplierViewModel[];
  clonedOutsourcings: { [s: number]: ChooseSupplierViewModel; } = {};
  suppliers: [];
  supplierItems: SelectItem[] = new Array<SelectItem>();
  ngOnInit(): void {
    console.log(this.workflowid);
    this.initForm();
  }
  constructor(injector: Injector,
    private route: ActivatedRoute,
    private _OutsourcingWorkFlowServiceProxy: OutsourcingWorkFlowServiceProxy,
    private _taskServiceProxy: TaskServiceProxy,
    private _userServiceProxy: UserServiceProxy,
    private _outsouringServiceProxy: OutsouringServiceProxy,
    private _supplierQuotationServiceProxy: SupplierQuotationServiceProxy,
    private _workflowService: WorkflowServiceProxy) {
    super(injector);
    this.detailsprimengTableHelper = new PrimengTableHelper();

  }

  initForm(): void {
    this._OutsourcingWorkFlowServiceProxy.getOutsourcingWorkFlow(this.workflowid).subscribe(resultdata => {
      this.workflow = resultdata.workFlowDto;
      this.suppliers = this.workflow.supplierUnit.split(',');
      this.suppliers.forEach(element => {
        console.log(element);
        console.log(this.supplierItems);
        this.supplierItems.push({ label: element, value: element });
      });
      this.canvasWidth = this.suppliers.length * 230;
      console.log(this.canvasWidth)
      this._outsouringServiceProxy.getOutsourcingsForChooseSupplier(this.workflowid).subscribe(dto => {
        this.datatablevalues = dto;
        this.rows = dto.length;
        console.log(dto);
        this.active = true;
        this.isLoading = false;
      })

    })
  }

  getSupplierQuotation(suppliername: string, rowindex: number): string {
    let currentD = this.datatablevalues[rowindex];
    let quotation = currentD.quotations.find((element) => (element.supplier === suppliername));
    if (quotation)
      return quotation.quotation;
    return '-';
  }
  audityes(): void {
    this.datatablevalues.forEach(element => {
      if (element.supplierName == undefined) {
        this.notify.info(element.taskName + '未选择供方！');
        return;
      }
    });

    this._OutsourcingWorkFlowServiceProxy.outsourcingFlow_ChooseSupplier(this.workflowid).subscribe(dto => {
      console.log(dto);
      this.out.emit(dto);
    });
  }

  closemodel(): void {
    this.out.emit('保存');
  }

  onRowEditInit(quotationmodel: ChooseSupplierViewModel) {
    console.log(quotationmodel);
    this.clonedOutsourcings[quotationmodel.taskForModelId.toString()] = { ...quotationmodel };
  }

  onRowEditSave(quotationmodel: ChooseSupplierViewModel) {
    console.log(quotationmodel);
    if (quotationmodel.outsouringAmount > 0) {
      delete this.clonedOutsourcings[quotationmodel.taskForModelId.toString()];

      this._outsouringServiceProxy.updateOutsourcingChooseSupplier(quotationmodel).subscribe(result => {
        if (result == "ok") {
          this.notify.info(this.l('SavedSuccessfully'));
        }
      })
    } else {
      this.notify.info('申请数量不能小于0');
    }
  }

  onRowEditCancel(quotationmodel: ChooseSupplierViewModel, index: number) {
    console.log(this.clonedOutsourcings[quotationmodel.taskForModelId.toString()]);
    this.datatablevalues[index] = this.clonedOutsourcings[quotationmodel.taskForModelId.toString()];
    delete this.datatablevalues[quotationmodel.taskForModelId];
  }

  changesuppler(evt, quotationmodel: ChooseSupplierViewModel) {
    console.log(evt);
    quotationmodel.supplierName = evt.value;
  }
}
